<template>
  <div class="item-one" ref="itemOne">
    <div class="title">
      <span>商户交易统计</span>
      <div>
        <el-button type="primary" v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8" @click="joinbill()">对账单</el-button>
        <el-button type="primary" v-if="userinfo.rolesId == 4 || userinfo.fid == 1304" @click="joinbill()">对账单</el-button>
        <el-button type="primary" :disabled='exxxx' @click="merchantexcel()"><i class="el-icon-download" ></i>导出</el-button>
        <el-button icon="el-icon-refresh"></el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem">
            <div class="block">
              <el-date-picker
                v-model="date"
                type="daterange"
                align="right"
                unlink-panels
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :clearable = 'false'
                :default-time="['00:00:00', '23:59:59']"
                :picker-options="pickerOptions2">
              </el-date-picker>
              <el-select v-if="userinfo.rolesId != 5 && userinfo.rolesId != 6"  v-model="channelType" placeholder="通道类型">
                <!-- <el-option keys="1" label="全部" value=""></el-option> -->
                  <el-option v-for="(item,index) in channelslist" :key="index" :label="item.options" :value="item.code"></el-option>
              </el-select>
            </div>
          </div>
          <div class="leftitem" v-if="userinfo.rolesId != 4" >
            <el-form ref="conditions" :model="conditions">
              <el-select v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8 || userinfo.rolesId == 9" class="servicelevel" v-model="conditions.servicelevel" placeholder="服务商级别" @change="servicelevel">
                <el-option keys="1" label="一级服务商" :value="1"></el-option>
                <el-option keys="2" label="二级服务商" :value="2"></el-option>
              </el-select>
              <el-autocomplete v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8 || userinfo.rolesId == 2 || userinfo.rolesId == 9" class="servicename" v-model.trim="conditions.servicename"  :fetch-suggestions="querySearch" placeholder="服务商名称" @select="serviceid"></el-autocomplete>
              <el-autocomplete v-if="userinfo.rolesId != 5" class="BDname" v-model.trim="conditions.BDname" :fetch-suggestions="BDname" placeholder="业态" @select="BDid"></el-autocomplete>
            </el-form>
          </div>
          <div class="leftitem">
            <el-select  v-model="type" placeholder="支付类型">
                <el-option keys="1" label="微信" :value="400"></el-option>
                <el-option keys="2" label="支付宝" :value="300"></el-option>
                <el-option keys="3" label="银行卡" :value="200"></el-option>
                <el-option keys="3" label="云闪付" :value="600"></el-option>
                
              </el-select>
          </div>
        </div>
        <div class="rightBox">
          <div class="rightitem" v-if="userinfo.rolesId != 5">
            <el-form ref="conditions" :model="conditions" label-width="80px">
             <el-input class="merchants" v-model.trim="conditions.keywords" placeholder="商户号/商户名"></el-input>
            </el-form>
          </div>
          <div class="rightitem" v-if="userinfo.rolesId == 1 || userinfo.rolesId == 2 || userinfo.rolesId == 8 || userinfo.rolesId == 9">
            <el-form label-width="80px">
              <!-- <el-select class="servicename1" v-model="dimension"  placeholder="选择维度" @change="dimension_menu">
                <el-option keys="1" label="一级服务商" :value="2" v-if="userinfo.rolesId !== 2 "></el-option>
                <el-option keys="2" label="二级服务商" :value="3"></el-option>
                <el-option keys="2" label="业态" :value="4"></el-option>
                <el-option keys="2" label="商户" :value="5"></el-option>
                <el-option keys="2" label="门店" :value="6"></el-option>
              </el-select> -->
              <el-autocomplete class="servicename1" v-model.trim="tagname" :fetch-suggestions="querySearch_tag" @select="serviceid_tag" placeholder="商户标签名" :trigger-on-focus="false"></el-autocomplete>
            </el-form>
          </div>
          <div class="rightitem">
            <el-button icon="el-icon-search" type="primary" @click="soso">搜索</el-button>
            <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
          </div>
        </div>
      </div>
       <div class="stitle">合计:</div>
       <div class="statistical">
        <div class="statisticalitem">
            <div>总交易金额</div>
            <div><span class="red">{{datainfo.totalFee}}</span>元</div>
            <!-- <div>日环比<span class="blue">-15.5%</span></div> -->
        </div>
         <div class="statisticalitem">
            <div>总手续费</div>
            <div><span class="red">{{datainfo.fee}}</span>元</div>
            <!-- <div>日环比<span class="blue">-2.5%</span></div> -->
        </div>
         <div class="statisticalitem">
            <div>总交易笔数</div>
            <div><span class="red">{{datainfo.total}}</span>笔</div>
            <!-- <div>日环比<span class="blue">-2.5%</span></div> -->
        </div>
         <div class="statisticalitem">
            <div>总结算金额</div>
            <div><span class="red">{{datainfo.balance}}</span>元</div>
            <!-- <div>日环比<span class="blue">-15.5%</span></div> -->
        </div>
         <div v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8 || userinfo.rolesId == 2" class="statisticalitem">
            <div>平台-一级分润</div>
            <div><span class="red">{{datainfo.agent1Profit}}</span>元</div>
            <!-- <div>日环比<span class="blue">-15.5%</span></div> -->
        </div>
         <div v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8 || userinfo.rolesId == 2 || userinfo.rolesId == 3" class="statisticalitem">
            <div>一级-二级分润</div>
            <div><span class="red">{{datainfo.agent2Profit}}</span>元</div>
            <!-- <div>日环比<span class="blue">-15.5%</span></div> -->
        </div>
        <div v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8 || userinfo.rolesId == 2 || userinfo.rolesId == 3 || userinfo.rolesId == 4" class="statisticalitem">
            <div>二级-三级分润</div>
            <div><span class="red">{{datainfo.bdProfit}}</span>元</div>
            <!-- <div>日环比<span class="blue">-15.5%</span></div> -->
        </div>
      </div>
      <div class="tableBox">
        <el-table
          ref="multipleTable"
          :data="merchantarr"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="tableHeaderColor"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55"></el-table-column>
         <el-table-column align="center" type="index" label="序号"></el-table-column>
         <el-table-column prop="merchantNo" label="商户号"></el-table-column>
         <el-table-column prop="merchantName" label="商户名"></el-table-column>
         <el-table-column prop="totalFee" label="交易总额"></el-table-column>
         <el-table-column prop="fee" label="手续费"></el-table-column>
         <el-table-column prop="balance" label="结算总金额"></el-table-column>
         <el-table-column prop="total" label="交易总笔数"></el-table-column>
         <el-table-column v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8 || userinfo.rolesId == 2" prop="agent1Profit" label="平台-一级分润"></el-table-column>
         <el-table-column v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8 || userinfo.rolesId == 2 || userinfo.rolesId == 3" prop="agent2Profit" label="一级-二级分润"></el-table-column>
         <el-table-column v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8 || userinfo.rolesId == 2 || userinfo.rolesId == 3 || userinfo.rolesId == 4"  prop="bdProfit" label="二级-三级分润"></el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="joininfo(scope.row.merchantId)">详细</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="combined"
            :current-page.sync="cur_page"
          ></el-pagination>
        </div>
      </div>
      <br>
      <br>
      
    </div>
  </div>
</template>

<script>
import { getservice, merchantlist,merchantstatistics,getBD,merchantexcel,getlabelTagList,getDimensionTagList,dictionarylist} from "@/api/api";
export default {
  name:"baseform",
  data: function() {
    return {
      type:'',
      channelType:'',
      exxxx: false,
      tableData: [],
      cur_page: 1,
      cur_size: 10,
      multipleSelection: [],
      visible: false,
      servicearr:[],
      merchantarr:[],
      combined:10,
      pageCount:'',
      channelslist:[],
      datainfo:{
        totalFee:'',
        fee:'',
        total:'',
        balance:'',
        agent1Profit:'',
        agent2Profit:'',  
        bdProfit:'',
      },
      userinfo:"",
      date:"",
      loading: true,
      conditions: {
        servicelevel: "",
        servicename: "",
        stardate:"",
        enddate:"",
        serviceid:"",
        aisle:"",
        shopno:"",
        BDname:"",
        keywords:""
      },
      dimension:'',//选择维度
      tagname:'',//标签名
      label_all:[],//标签模糊查询
      tagId:'',
      pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
    };
  },
  created() {
    this.dictionarylist()
     this.userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
    this.$store.dispatch("getNewNum", 6);
    // console.log(this.$store.state.changableNum);
    // console.log(this.$store.state.showFooter);
    // console.log(this.$store.state.logininfo);
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
    const year=start.getFullYear();
    const month=start.getMonth()+1;
    const date=start.getDate();
    const date1 = year+'-'+month+ '-'+date
    const date2 = year+'-'+month+ '-'+date
    this.date = [date1,date2]
  
    this.merchantstatistics('1')
    if(this.userinfo.rolesId == 1){
      this.conditions.servicelevel = 1
      this.servicelevel('1')
    }
    if(this.userinfo.rolesId == 2){
      this.conditions.servicelevel = 2
      this.servicelevel('2')
    }else if(this.userinfo.rolesId == 3){
      this.getBD(this.userinfo.fid)
    }
    // this.dimension_menu(5)
    
  },
  methods: {
    // 跳转对账单
    joinbill(){
      this.$router.push("/bill");
    },
     // 获取所有通道type
    dictionarylist(){
      dictionarylist().then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          this.channelslist = res.data
        }
      });
    },
     //修改thead 背景色
     tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
          return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
        }
      },
    
    joininfo(val) {
      // console.log(val)
      this.$router.push({ path: "/businessstatisticsinfo",
          query: { 
                no: val,
                date: this.date,
                channelType: this.channelType
            } 
      });
    },
    // 刷新
    refresh() {
      this.$router.replace({
        path: "/refresh",
        query: {
          t: Date.now()
        }
      });
    },
    // 分页导航
    handleCurrentChange(val) {
        if(this.conditions.servicelevel == 1){
        this.merchantstatistics('1')
      }else if(this.conditions.servicelevel == 2){
        this.merchantstatistics('2')
      }else{
        this.merchantstatistics('2')
      }
      this.cur_page = val;
       this.$nextTick(() => {
         document.querySelectorAll('.content')[0].scrollTop = '0'
      });

    },
    // 分页数量
    sizechange(val){
      this.cur_size = val
       if(this.conditions.servicelevel == 1){
        this.merchantstatistics('1')
      }else if(this.conditions.servicelevel == 2){
        this.merchantstatistics('2')
      }else{
        this.merchantstatistics('2')
      }
       
       this.$nextTick(() => {
         document.querySelectorAll('.content')[0].scrollTop = '0'
      });
       
    },
    //多选框
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val;
    },
    //  重置
    reset() {
      this.conditions.servicelevel =  ''
      this.conditions.servicename =  ''
      this.conditions.stardate = ''
      this.conditions.enddate = ''
      this.conditions.serviceid = ''
      this.wx1code = ''
      this.cur_page = 1
      this.conditions.BDname = ''
      this.conditions.keywords = ''
      this.conditions.BDid = ''
      this.channelType = ''
      this.type = ''
      this.dimension = ''
      this.tagname = ''
      this.tagId = ''
      if(this.userinfo.rolesId == 2){
        this.conditions.servicelevel =  2
      }
      },
       // 业态
    BDname(queryString, cb){
      let BDarr = this.BDarr;
      let results = queryString
        ? BDarr.filter(this.createFilter(queryString))
        : BDarr;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
     BDid(item) {
      this.conditions.BDid = item.id
    },
    serviceid(item){
      this.conditions.serviceid = item.id
      this.getBD(item.id)
    },
     getBD(id){
      this.BDarr = []
        getBD(
          {agentid: id
          }).then(res => {
          console.log(res);
          for(var i=0;i<res.data.rows.length;i++){
            this.BDarr.push({'value':res.data.rows[i].name,'id':res.data.rows[i].id})
          }
        });
    },
    // 搜索
    soso(){
      this.loading =true
       this.cur_page = 1
       if(!this.conditions.servicename){
        this.conditions.serviceid = ''
      }
       if(!this.conditions.BDname){
        this.conditions.BDid = ''

      }
      if(this.conditions.servicelevel == 1){
        this.merchantstatistics('1')
      }else if(this.conditions.servicelevel == 2){
        this.merchantstatistics('2')
      }else{
        this.merchantstatistics('2')
      }
      
    },
    // 服务商名称
     querySearch(queryString, cb) {
      let servicearr = this.servicearr;
      let results = queryString
        ? servicearr.filter(this.createFilter(queryString))
        : servicearr;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
    // 服务商级别
    servicelevel(val){
      this.servicearr = []
       getservice({
          type: val,
        }).then(res => {
          console.log(res);
          for(var i=0;i<res.data.rows.length;i++){
            this.servicearr.push({'value':res.data.rows[i].agentname,'id':res.data.rows[i].id})
          }
        });

    },
  
    // 商户交易统计
    merchantstatistics(level){

      // console.log(this.conditions)
      let sosolist = {}
      if(level == 1){
        sosolist ={
          page: this.cur_page,
          size: this.cur_size,
          agent1Id: this.conditions.serviceid,
          startDate: this.date[0],
          endDate: this.date[1],
          keywords: this.conditions.keywords,
          bdId: this.conditions.BDid,
          channelType: this.channelType,
          type: this.type,
          tagId: this.tagId
        }
      }else if(level ==2){
        sosolist = {
          page: this.cur_page,
          size: this.cur_size,
          agent2Id: this.conditions.serviceid,
          startDate: this.date[0],
          endDate: this.date[1],
          keywords: this.conditions.keywords,
          bdId:this.conditions.BDid,
          channelType: this.channelType,
          type: this.type,
          tagId: this.tagId
        }
      }
      console.log(sosolist)
      merchantstatistics(sosolist).then(res => {
          // console.log(res);
          if(res.code == 405){
           sessionStorage. removeItem('token')
            this.$router.push('/login');
          }else if(res.code == 200){
            this.merchantarr = res.data.statistics
            this.datainfo = res.data
            this.combined = res.pageInfo.recordCount
            this.pageCount = res.pageInfo.pageCount
            this.loading = false
          }else if(res.code == 500){
            this.$message.error(res.message);
          }
          
        });
    },
    //维度查询标签
    dimension_menu(v){
      this.label_all = []
      getDimensionTagList({
        roleId: v
      }).then(res => {
        if(res.code == 405){
          sessionStorage. removeItem('token')
          this.$router.push('/login');
        }else if(res.code == 200){
          for(var i=0;i<res.data.length;i++){
            this.label_all.push({'value':res.data[i].tagName,'id':res.data[i].tagId})
          }
        }else{
          this.$message.error(res.message);
        }
      })
    },
    //标签模糊
    querySearch_tag(queryString,cb){
      // let servicearr = this.label_all;
      // let results = queryString
      //   ? servicearr.filter(this.createFilter(queryString))
      //   : servicearr;
      // // 调用 callback 返回建议列表的数据
      // cb(results);
       let that = this
      getDimensionTagList({
        roleId: 5,
        tagwords: this.tagname
      }).then(res => {
        if(res.code == 405){
          sessionStorage. removeItem('token')
          that.$router.push('/login');
        }else if(res.code == 200){
          that.label_all = []
          for(var i=0;i<res.data.length;i++){
            that.label_all.push({'value':res.data[i].tagName,'id':res.data[i].tagId})
          }
          let servicearr = that.label_all;
          let results = queryString
            ? servicearr.filter(that.createFilter(queryString))
            : servicearr;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }else{
          that.$message.error(res.message);
        }
      })
    },
    serviceid_tag(item){
      console.log(item)
      this.tagId = item.id
    },
    // 导出
    merchantexcel(){
      this.eeeex = true;
      const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      let level = this.conditions.servicelevel;
      let sosolist = {}
      if(level == 1){
        sosolist ={
          page: this.cur_page,
          size: this.cur_size,
          agent1Id: this.conditions.serviceid,
          startDate: this.date[0],
          endDate: this.date[1],
          keywords: this.conditions.keywords,
          bdId: this.conditions.BDid,
          channelType: this.channelType,
          type: this.type,
          tagId: this.tagId
        }
      }else if(level ==2){
        sosolist = {
          page: this.cur_page,
          size: this.cur_size,
          agent2Id: this.conditions.serviceid,
          startDate: this.date[0],
          endDate: this.date[1],
          keywords: this.conditions.keywords,
          bdId:this.conditions.BDid,
          channelType: this.channelType,
          type: this.type,
          tagId: this.tagId
        }
      }else{
        sosolist = {
          page: this.cur_page,
          size: this.cur_size,
          agent2Id: this.conditions.serviceid,
          startDate: this.date[0],
          endDate: this.date[1],
          keywords: this.conditions.keywords,
          bdId:this.conditions.BDid,
          channelType: this.channelType,
          type: this.type,
          tagId: this.tagId
        }
      }
       merchantexcel(sosolist).then(res => {
          if(res.code == 405){
            sessionStorage. removeItem('token')
            this.$router.push('/login');
             loading.close();
             this.exxxx = false;
          }else if(res.code == 200){
            let elink = document.createElement('a');
            elink.href = res.data;
            elink.click();
            this.exxxx = false;
            loading.close();
            
          }else{
            this.$message.error(res.message);
            loading.close();
            this.exxxx = false;
          }
        })


    }
  }
};
</script>
<style scoped lang='less'>
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 50%;
}
.tableBox {
  margin-top: 20px;
}
.servicename{
  width: 43%;
}
.servicename1{
  width: 60%;
}
.servicelevel{
  width: 23.5%;
}
.width20{
    width: 20%;
}
.red {
  color: #f9607d;
}
.blue{
    color: #01AAEF;
}
.stitle{
    padding: 5px 0;
    font-size: 18px;
}
.statistical {
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: #374459;
  color: #fff;
  padding: 12px;
  box-sizing: border-box;
  .statisticalitem{
      flex: 1;
      text-align: center;
      border-right: 1px solid rgba(255, 255, 255, 0.445);
      font-size: 13px;
      line-height: 180%;
      &:nth-last-child(1){
          border-right: none;
      }
      .red {
        color: #f9607d;
        font-size: 18px;
      }
      .blue{
            color: #01AAEF;
            font-size: 18px;
        }
  }
}
// .BDname{
//   width: 20%;
// }
</style>